home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2448 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: oxy.rust.net!usenet
  2. From: ebennett@rust.net
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Sun, 21 Jan 1996 19:49:30 GMT
  6. Organization: Rust Net - High Speed Internet in Detroit  810-642-2276
  7. Message-ID: <4dtqpq$sl2@oxy.rust.net>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net> <9601201820.AA01752@dxmint.cern.ch>
  9. NNTP-Posting-Host: liv-11.rust.net
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Dan Pop <danpop@mail.cern.ch> wrote:
  13.  
  14. >ebennett@rust.net writes:
  15.  
  16. >>Given some number, there is a neat trick to generate a mask which will
  17. >>have exactly one bit set in it.  The bit set will be the least
  18. >>significant non-zero bit in the original number:
  19. >>
  20. >>    mask = ~number & number;
  21. >>
  22. >>Now, if number contained a single non-zero bit (and is therefore a
  23. >>power of 2),  mask will be equal to number.  Therefore:
  24. >>
  25. >>   if (number == (~number & number))
  26. >>   {
  27. >>        /* number is a power of 2 */
  28. >>   }
  29. >>
  30. >>Try it, you'll like it!
  31.  
  32. >I don't think so.  ~number & number will _always_ give 0.  -number & number
  33. >will actually work, except for the case when number == 0.  That is,
  34. >assuming a two's complement implementation.  On a one's complement or
  35. >sign-magnitude implementation it won't work at all.
  36.  
  37. >Yet another guy who makes a fool of himself because he's too lazy to
  38. >test his solution before posting.
  39.  
  40. >Dan
  41.  
  42. You are correct in that I made a typo in my message.  ~ should have
  43. been -.  There are also some limitations which did not occur to me,
  44. which you have rightly pointed out.
  45.  
  46. I agree with the problem with 0, and that is easily checked for.
  47. Where would you run into a one's complement or sign-magnitude
  48. implementation?
  49.  
  50. However, I do not feel that I made a fool of myself. Most of us are
  51. not perfect as you apparently are. The rest of us make mistakes, and
  52. learn from them. That does not make us fools.
  53.  
  54. Earl
  55.  
  56.  
  57.